<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getCategories } from "@/api/user/category";
import { ElCard } from "element-plus";

interface Category {
  id: number;
  name: string;
  rank: number;
}

const categories = ref<Category[]>([]);
const activeCategory = ref<number>(1);

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategories();
    if (res.data && res.data.categories) {
      categories.value = res.data.categories;
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
  }
};

// 定义emit事件
const emit = defineEmits(["category-change"]);

// 处理分类点击
const handleCategoryClick = (categoryId: number) => {
  activeCategory.value = categoryId;
  emit("category-change", categoryId);
};

onMounted(() => {
  fetchCategories();
});
</script>

<template>
  <div class="category-list">
    <el-card
      v-for="category in categories"
      :key="category.id"
      class="category-card"
      :class="{ active: activeCategory === category.id }"
      @click="handleCategoryClick(category.id)"
    >
      <div class="category-content">
        {{ category.name }}
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.category-list {
  display: flex;
  flex-wrap: nowrap;
  gap: 10px;
  padding: 10px;
  overflow-x: auto;
  width: 100%;
}

.category-card {
  flex: 0 0 auto;
  min-width: 100px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.category-card.active {
  border-bottom: 2px solid #409eff;
  background-color: #ecf5ff;
}

.category-content {
  padding: 8px;
  font-size: 14px;
  color: #606266;
  text-align: center;
}

.category-card.active .category-content {
  color: #409eff;
}
</style>
